/**
 * @(#)AbstractHttpXmlEncoder.java, 2018/12/27
 * <p/>
 * Copyright 2018 Netease, Inc. All rights reserved.
 * NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.chengzhi.netty.http.xml;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import java.io.StringWriter;
import java.nio.charset.Charset;


/**
 * @author 阮承志(wb.ruanchengzhi @ mesg.corp.netease.com)
 **/
public abstract class AbstractHttpXmlEncoder<T> extends MessageToMessageEncoder<T> {

    IBindingFactory factory = null;

    StringWriter writer = null;

    final static String CHARSET_NAME = "UTF-8";

    final static Charset UTF_8 = Charset.forName(CHARSET_NAME);

    protected ByteBuf encode0(ChannelHandlerContext ctx, Object msg) throws Exception {
        factory = BindingDirectory.getFactory(msg.getClass());
        writer = new StringWriter();
        IMarshallingContext context = factory.createMarshallingContext();
        context.setIndent(2);
        context.marshalDocument(msg, CHARSET_NAME, null, writer);
        String xml = writer.toString();
        writer.close();
        writer = null;
        ByteBuf byteBuf = Unpooled.copiedBuffer(xml, UTF_8);
        return byteBuf;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (null != writer) {
            writer.close();
            writer = null;
        }
    }
}
